package com.yekong.house.web.controller;

import com.yekong.house.biz.service.AgencyService;
import com.yekong.house.biz.service.impl.UserServiceImpl;
import com.yekong.house.common.constants.CommonConstants;
import com.yekong.house.common.model.User;
import com.yekong.house.biz.service.UserService;
import com.yekong.house.common.utils.HashUtil;
import com.yekong.house.common.vo.ResultMsg;
import com.yekong.house.web.interceptor.UserContext;
import com.yekong.house.web.utils.UserHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AgencyService agencyService;

    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    /*@GetMapping("/users")
    public List<User> getUsers(){
        return userService.getUsers();
    }*/



    @GetMapping("/accounts/register")
    public String getRegister(HttpServletRequest request,ModelMap modelMap){
        User user = UserContext.getUser();
        if(user!=null){
            String url = request.getParameter("target");
            return "redirect:/index?"+ResultMsg.errorMsg("你已经登陆！").asUrlParams();
        }
        modelMap.put("agencyList",  agencyService.getAllAgency());
        return "/user/accounts/register";
    }


    /**
     * 1.注册验证 2.发送邮件 3.验证失败重定向到注册页面
     * 注册页获取： 根据  account  对象为依据判断是否注册页获取请求
     * @param account
     * @param modelMap
     * @return
     */
    @PostMapping("/accounts/register")
    public String accountsRegister(User account,ModelMap modelMap) {
        //用户验证
        ResultMsg resultMsg = UserHelper.validate(account);
        if(resultMsg.isSuccess()&&  userService.addAccount(account)){
            modelMap.put("email",account.getEmail());
            return "/user/accounts/registerSubmit";
        }else{
            return "redirect:/accounts/register?"+resultMsg.asUrlParams();
        }
    }


    // 激活用户
    @GetMapping("/accounts/verify")
    public String verify(String key){
        boolean result = userService.enable(key);
        if(result){
            return "redirect:/index?"+ResultMsg.successMsg("激活成功!").asUrlParams();
        }else{
            return "redirect:/accounts/register?"+ResultMsg.errorMsg("激活失败，请请确认链接是否过期!");
        }
    }

    /**
     * 登陆接口
     */
    @RequestMapping("/accounts/signin")
    public String signin(HttpServletRequest req){
        String username = req.getParameter("username");
        String password  = req.getParameter("password");
        String target = req.getParameter("target");
        if(username== null||password ==null){
            req.setAttribute("target",target);
            return "/user/accounts/signin";
        }
        User user = userService.auth(username,password);
        if(user == null){
            return "redirect:/accounts/signin?"+"target="+target+"&username="+username+"&"+ResultMsg.errorMsg("用户名或密码错误").asUrlParams();
        }else{
            user.setPasswd(null);
            HttpSession session =  req.getSession(true);
            session.setAttribute(CommonConstants.USER_ATTRIBUTE,user);
            session.setAttribute(CommonConstants.PLAIN_USER_ATTRIBUTE,user);
            return StringUtils.isNoneBlank(target)?"redirect:"+target:"redirect:/index";
        }
    }

    /**
     *  登出
     * @param request
     * @return
     */

    @GetMapping("/accounts/logout")
    public String logout(HttpServletRequest request){
        HttpSession httpSession = request.getSession(true);
        httpSession.invalidate();
        return "redirect:/index";
    }


    /**
     * 1. 能够提供页面信息
     * 2. 更新用户信息
     *
     */

    @GetMapping("/accounts/profile")
    public String personProfile(HttpServletRequest request){
        return "/user/accounts/profile";
    }


    /**
     * 个人页面，post请求
     *
     * @param request
     * @param updateUser
     * @param model
     * @return
     */
    @PostMapping("/accounts/profile")
    public String saveProfile(HttpServletRequest request,User updateUser, ModelMap model) {

/*        if(updateUser.getEmail()== null){
            return "/user/accounts/profile";
        }*/
        logger.info("post请求");
        userService.updateUser(updateUser,updateUser.getEmail());
        //更新完毕要返回更新后的用户信息
        User query = new User();
        query.setEmail(updateUser.getEmail());
        List<User> users = userService.getUserByQuery(query);
        request.getSession(true).setAttribute(CommonConstants.USER_ATTRIBUTE,users.get(0));
        return "redirect:/accounts/profile?"+ResultMsg.successMsg("更新成功");
    }


    /**
     *  修改密码操作
     *
     * @param email
     * @param passwd
     * @param newPasswd
     * @param confiirmPasswd
     * @param model
     * @return
     */
    @RequestMapping("/accounts/changePasswd")
    public String changePassword(String email,String passwd,String newPasswd,String confiirmPasswd,ModelMap model){
        User user = userService.auth(email,passwd);
        if(user == null || confiirmPasswd.equals(newPasswd)){
            return "/redirect:/accounts/profile?"+ResultMsg.errorMsg("密码错误");
        }
        User updateUser = new User();
        updateUser.setPasswd(HashUtil.encryPassword(newPasswd));
        userService.updateUser(updateUser,updateUser.getEmail());
        return "redirect:/accounts/profile?"+ResultMsg.successMsg("更新成功").asUrlParams();
    }

    /**
     * 1. 忘记密码
     * 2. 发送重置密码到邮箱
     *
     * @param username
     * @param modelMap
     * @return
     */
    @RequestMapping("/accounts/remember")
    public String remember(String username,ModelMap modelMap){
        if(StringUtils.isBlank(username)){
            return "redirect:/accounts/signin?"+ResultMsg.errorMsg("邮箱不能为空").asUrlParams();
        }
        userService.resetNotify(username);
        modelMap.put("email",username);
        return "/user/accounts/remember";
    }

    /**
     * 1. 重置面页面
     *
     * @param key
     * @param modelMap
     * @return
     */
    @RequestMapping("/accounts/reset")
    public String reset(String key,ModelMap modelMap){
        String email = userService.getResetEmail(key);
        if(StringUtils.isBlank(email)){
            return "redirect:/accounts/signin?"+ ResultMsg.errorMsg("重置链接已过期").asUrlParams();
        }
        modelMap.put("email",email);
        modelMap.put("success_key",key);
        return "/user/accounts/reset";
    }


    @RequestMapping("/accounts/resetSubmit")
    public String resetSubmit(HttpServletRequest request,User user){
        ResultMsg resultMsg = UserHelper.validateResetPassword(user.getKey(),user.getPasswd(),user.getConfirmPasswd());
        // 如果结果消息有误，跳转回密码重置页面
        if (!resultMsg.isSuccess() ) {
            String suffix = "";
            if (StringUtils.isNotBlank(user.getKey())) {
                suffix = "email=" + userService.getResetEmail(user.getKey()) + "&key=" +  user.getKey() + "&";
            }
            return "redirect:/accounts/reset?"+ suffix  + resultMsg.asUrlParams();
        }
        User updatedUser =  userService.reset(user.getKey(),user.getPasswd());
        request.getSession(true).setAttribute(CommonConstants.USER_ATTRIBUTE, updatedUser);
        return "redirect:/index?" + resultMsg.asUrlParams();
    }

}


